/*
 * Copyright © 2012-2013 Subhodip Kumar <subhodip.kumar@gmail.com>
 * Papr. 1.0
 */

var content="null";
var orig_url= "";

var REQUEST_HANDLERS = {
  savePage: function(request, sendResponse, sender) {
    var tabID = sender.tab.id; 
  	content=request.content;
  	orig_url=request.orig_url;
  	console.log(orig_url);
  	var pop = chrome.extension.getViews({type: "popup"});
  	if (pop.length != 0) {
  	var popup = pop[0];
  	var num = Math.round(Math.random() * 10000);
  	var url=orig_url;
   	var shortUrl=self.shortenUrl(url);
   	var title=request.header;
   	var fevicon=null;//not req
   	var orig=orig_url;
   	popup.saveDirect(num, url, shortUrl, title, fevicon, content, orig);
   	console.log("direct saved");
  	}
  	console.log("page saved!!!");
  },

  downloadFile: function(request, sendResponse) {
    try {
      var req = new XMLHttpRequest();
      req.open('GET', request.href);
      if (request.binary) req.overrideMimeType('text/plain; charset=x-user-defined');
      req.onreadystatechange = function() {
        if (req.readyState == 4) {
          if (req.status == 200) {
            request.contentType = req.getResponseHeader('Content-Type');
            request.data = req.responseText;
          }
          else {
            console.error('Status: ' + req.status);
            request.error = "Unexpected error";
          }
          sendResponse(request);
        }
      }
      req.send();
    }
    catch (e) {
      console.error('Download error: ' + e.message);
      request.error = e.message;
      sendResponse(request);
    }
  },

  savePageRequest: function(request, sendResponse) {
    var tabID = request.tabID;
    console.log("before exec scrpt");
    chrome.tabs.executeScript(tabID, {file: 'conten.js'}, function() {
      console.log("save page req sent!!")
    });
    sendResponse();
  },
};
var shortenUrl=function(url) {
        	var start=url.search("//");
			start=start+2;
			
			url=url.substring(start);
			
			end=url.search("/");
			short_url=url.substring(0,end);
			return short_url;
};



function messageListener(request, sender, sendResponse) {
  var handler = REQUEST_HANDLERS[request.type];
  if (handler)
    handler(request, sendResponse, sender);
}

var fb_init=function(link,title){

console.log("get called");


var Url='https://www.facebook.com/dialog/oauth?client_id=221834854613553&response_type=token&scope=publish_stream&redirect_uri=http://www.facebook.com/connect/login_success.html'
chrome.tabs.create({url: Url });

var successURL = 'www.facebook.com/connect/login_success.html';


var onFacebookLogin = function(link,title){
    console.log(link);
	console.log(title);
    chrome.tabs.query({}, function(tabs) { // get all tabs from every window
      for (var i = 0; i < tabs.length; i++) {
        if (tabs[i].url.indexOf(successURL) !== -1) {
          // below you get string like this: access_token=...&expires_in=...
          var params = tabs[i].url.split('#')[1];

          // in my extension I have used mootools method: parseQueryString. The following code is just an example ;)
          var accessToken = params.split('&')[0];
          accessToken = accessToken.split('=')[1];
          localStorage.setItem('accessToken', accessToken);
          chrome.tabs.remove(tabs[i].id);//acess token saved

          var token=localStorage.getItem('accessToken');
          console.log("token:"+token);
          //post to  feed
			title= encodeURIComponent(title);
			console.log("title:"+title);
			console.log("link:"+link);
			
			var postUrl='https://www.facebook.com/dialog/feed?app_id=221834854613553&link='+link+'&name='+title+'&redirect_uri=https://facebook.com/me';
			
           	chrome.tabs.create({url: postUrl });
        
        	console.log("post done!!!");
        	
        	//
        	/*var redirect_uri='https://google.com/robots.txt';
        	chrome.tabs.query({}, function(tabs) {
        	for (var i = 0; i < tabs.length; i++) {
        	if (tabs[i].url.indexOf(redirect_uri) !== -1) {
        	
        				chrome.tabs.remove(tabs[i].id);//remove the redirect url
        			}
        		};
        });//remove the redirect uri*/
        //add notification here..........
        }
      };
    });  
  };


chrome.tabs.onUpdated.addListener(function(){onFacebookLogin(link,title);});

};


// notify test

var user_notify=function(title,content){

var notification = window.webkitNotifications.createNotification(
    'http://dl.dropbox.com/spa/pldxabul5709z1u/papr./public/papr%2048.png',                      // The image.
    title, // The title.
    content      // The body.
  );
notification.show();
setTimeout(function(){notification.cancel();},5000);
};

var user_notify_first=function(title,content){

var notification = window.webkitNotifications.createNotification(
    'http://dl.dropbox.com/spa/pldxabul5709z1u/papr./public/papr%2048.png',                      // The image.
    title, // The title.
    content      // The body.
  );
notification.show();
};

/*var user_alert=function(title,content,_id){
console.log("alert");
var _notification = window.webkitNotifications.createNotification(
    'papr 48.png',                      // The image.
    title, // The title.
    content      // The body.
  );
_notification.onclose = function() {chrome.bookmarks.remove(String(_id));console.log("clicked");};
};*/

//notify test
  chrome.extension.onRequest.addListener(messageListener);
  console.log('Initialization finished');